﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;

using Microsoft.Win32;
using System.Configuration;
using System.Resources;
using System.Diagnostics;
using System.IO;
using System.Net.Sockets;
using System.Threading;
using ReadConfigNamespace;
using System.Text.RegularExpressions;
using System.Reflection;
using System.Net;

namespace IbnBazWeb
{
    public partial class Browser : Form
    {


        public static string serverName = "";


        public Browser()
        {
            killIftaaweb();
            getInstalledInstance();


            checkDataBaseAndRestoreIfNotFound();

            checkWeb();

            



            this.oIESettings = new object[2];
            RegistryKey key = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Internet Settings\Connections", true);
            object obj2 = key.GetValue("DefaultConnectionSettings");
            if (((byte)((Array)obj2).GetValue(9)) != 0)
            {
                this.oIESettings[0] = obj2;
                ((Array)obj2).SetValue((byte)0, 9);
                key.SetValue("DefaultConnectionSettings", obj2);
            }
            key.Close();
            key = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Internet Settings", true);
            obj2 = key.GetValue("AutoConfigURL");
            if (obj2 != null)
            {
                this.oIESettings[1] = obj2;
                key.DeleteValue("AutoConfigURL");
            }
            key.Close();
            this.components = null;
            this.InitializeComponent();
        }

        private void checkDataBaseAndRestoreIfNotFound()
        {
            bool dataCheck = checkDBExistence();
            if (!dataCheck)
            {
                createDataBase();
            }
        }

        private void createDataBase()
        {
            FileInfo  FileName = new FileInfo(System.Reflection.Assembly.GetExecutingAssembly().Location);
            string strDir = FileName.DirectoryName;
            if (!strDir.Trim().EndsWith("\\"))
                strDir = strDir.Trim() + "\\";

            string strDBFile = strDir + "AlIftaaGateDBIbnBaz.bak";

            string conn = "Data Source=" + serverName + ";Initial Catalog=master;Integrated Security=True";

            string dbNewLocation = Environment.SystemDirectory.Substring(0, 3);

            dbNewLocation = dbNewLocation + "IbnBazDB\\";
            if (!Directory.Exists(dbNewLocation))
                Directory.CreateDirectory(dbNewLocation);



            SqlConnection sqlConn = new SqlConnection(conn);

            try
            {
                if (sqlConn.State != ConnectionState.Open)
                    sqlConn.Open();

                

                string createDBSQL = "IF NOT EXISTS (SELECT name FROM sys.databases WHERE name = N'AlIftaaGateDBIbnBaz') " +
                                    "BEGIN " +
                                    "CREATE DATABASE [AlIftaaGateDBIbnBaz] ON  PRIMARY " +
                                    "( NAME = N'AlIftaaGateDBIbnBaz', FILENAME = N'" + dbNewLocation + "AlIftaaGateDBIbnBaz.mdf' , SIZE = 3072KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB ) " +
                                    " LOG ON  " +
                                    "( NAME = N'AlIftaaGateDBIbnBaz_log', FILENAME = N'" + dbNewLocation + "AlIftaaGateDBIbnBaz.LDF' , SIZE = 1024KB , MAXSIZE = 2048GB , FILEGROWTH = 10%) " +
                                    "END ";
               string restoreSQL=   "RESTORE DATABASE [AlIftaaGateDBIbnBaz] FROM  DISK = N'"+ strDBFile +"' WITH  FILE = 1,"+
                                    "NOUNLOAD,  REPLACE,  STATS = 10";

                Thread thNew = new Thread(doDialog);
                thNew.Start();


                SqlCommand sqlCreate = new SqlCommand(createDBSQL, sqlConn);
                sqlCreate.CommandTimeout = 900;
                sqlCreate.ExecuteNonQuery();


                SqlCommand sqlNewComm = new SqlCommand(restoreSQL, sqlConn);
                sqlNewComm.CommandTimeout = 900;
                sqlNewComm.ExecuteNonQuery();





                sqlConn.Close();


                thNew.Abort();

            }
            catch (Exception ex)
            {
                MessageBox.Show("خطأ لا يمكن تركيب الداتابيس!" + "\r\n" + ex.ToString());
                Environment.Exit(0);

            }
            finally
            {
                if (sqlConn.State == ConnectionState.Open)
                    sqlConn.Close();
            }

        }

        
        public static void doDialog()
        {
            frmWait frmNew = new frmWait();
            frmNew.ShowDialog();


        }

        

        private bool checkDBExistence()
        {
            string conn = "Data Source="+ serverName +";Initial Catalog=AlIftaaGateDBIbnBaz;Integrated Security=True";

            SqlConnection sqlConn = new SqlConnection(conn);

            try
            {
                if (sqlConn.State != ConnectionState.Open)
                    sqlConn.Open();


                SqlCommand scmd = new SqlCommand("select * from Page where 1<>1 ;", sqlConn);

                SqlDataAdapter sda = new SqlDataAdapter(scmd);
                DataTable dtRet = new DataTable();
                sda.Fill(dtRet);

                sqlConn.Close();

                if (dtRet.Columns["DisplayContent"] == null)
                    return false;
                else
                    return true;




            }
            catch
            {
                return false;
            }
            finally
            {
                if (sqlConn.State == ConnectionState.Open)
                    sqlConn.Close();
            }



        }

        //private void getInstalledInstance()
        //{
        //    RegistryKey rk = Registry.LocalMachine;
        //    RegistryKey sqlServer = null;
        //    try { sqlServer = rk.OpenSubKey("SOFTWARE\\Microsoft\\Microsoft SQL Server"); }
        //    catch { }
        //    if (sqlServer == null)
        //    {
        //        serverName = ".";
        //        return;
        //    }

        //    object keyValue = null;

        //    try { keyValue = sqlServer.GetValue("InstalledInstances"); }
        //    catch { }

        //    if (keyValue == null)
        //    {
        //        serverName = ".";
        //        return;
        //    }

        //    string[] strInstances = keyValue as string[];

        //    if (strInstances == null)
        //    {
        //        serverName = ".";
        //        return;
        //    }

        //    if (strInstances.Length == 0)
        //    {
        //        serverName = ".";
        //        return;
        //    }


        //    if (strInstances[0] == "MSSQLSERVER")
        //    {
        //        serverName = ".";
        //        return;
        //    }
        //    else
        //    {
        //        serverName = ".\\" + strInstances[0];
              
        //    }


            




        //}



        private void getInstalledInstance()
        {



            FileInfo fi = new FileInfo(Assembly.GetExecutingAssembly().Location);
            string dir = fi.DirectoryName;
            if (!dir.EndsWith("\\"))
                dir += "\\";



            string exeName = dir + "..\\..\\IbnBazSQL.exe";


            Process prNew = new Process();
            ProcessStartInfo psi = new ProcessStartInfo(exeName);
            psi.UseShellExecute = true;
            if (winVersion >= 5.2)
            {
                psi.Verb = "runas";
            }


            prNew.StartInfo = psi;

            string txtName = dir + "..\\..\\SqlIns.txt";

            if (!File.Exists(txtName))
            {
                prNew.Start();
                prNew.WaitForExit();
            }




            string[] str = new string[0];

            try
            {
                str = File.ReadAllLines(txtName);
            }
            catch
            {
                serverName = ".\\SQLEXPRESS";
                return;
            }



            if (str.Length == 0)
            {
                serverName = ".\\SQLEXPRESS";
                return;
            }


            foreach (string strIn in str)
            {
                if (strIn == ".\\SQLEXPRESS")
                {
                    serverName = strIn;
                    return;
                }
            }

            serverName = str[0];





        }



        private static double winVersion = ShohdiWindowsVersion.WindowsVersionClass.getWindowsVer();
        private static void checkWeb()
        {
            killIftaaweb();
            
                Process prStart = new Process();
                ProcessStartInfo prStartInfo = new ProcessStartInfo();
                FileInfo fiCurrent = new FileInfo(System.Reflection.Assembly.GetExecutingAssembly().Location);
                FileInfo startFile = new FileInfo(Path.Combine(fiCurrent.DirectoryName, @"..\common\Cassini\HarfWebCDInit.exe"));
                addFirewallAllowNew(startFile);
                addFirewallAllowOld(startFile);
                if (winVersion >= 5.2)
                {
                    prStartInfo.Verb = "runas";
                }
                prStartInfo.UseShellExecute = true;
                prStartInfo.FileName = startFile.FullName;
                prStart.StartInfo = prStartInfo;

                prStart.Start();

                
            
        }

        private static void killIftaaweb()
        {
            Process[] prArr = Process.GetProcessesByName("HarfWebCDInit");

            if (prArr.Length > 0)
                prArr[0].Kill();
        }

        private static  void addFirewallAllowOld(FileInfo startFile)
        {
            



            string fileName = Path.Combine(Environment.SystemDirectory, "netsh.exe") + " firewall add allowedprogram \"" + startFile.FullName + "\" \"HarfWebCDInit\" ENABLE";
            FileInfo fiCurrent = new FileInfo(Assembly.GetExecutingAssembly().Location);
            string strCurrentDir = fiCurrent.DirectoryName;
            if (!strCurrentDir.EndsWith("\\"))
                strCurrentDir += "\\";


            File.WriteAllText(strCurrentDir+ "run.bat", fileName);
            ProcessStartInfo prStartInfo = new ProcessStartInfo();
            prStartInfo.FileName = strCurrentDir+"run.bat";
            if (winVersion >= 5.2)
            {
                prStartInfo.Verb = "runas";
            }
            prStartInfo.UseShellExecute = true;
            prStartInfo.WindowStyle = ProcessWindowStyle.Hidden;
            Process prNew = new Process();
            prNew.StartInfo = prStartInfo;
            prNew.Start();
            prNew.WaitForExit();
        }


        private static void addFirewallAllowNew(FileInfo startFile)
        {
            string fileName = Path.Combine(Environment.SystemDirectory, "netsh.exe") + " advfirewall firewall add rule name=\"HarfWebCDInit\" dir=in action=allow program=\"" + startFile.FullName + "\" enable=yes";
            FileInfo fiCurrent = new FileInfo(Assembly.GetExecutingAssembly().Location);
            string strCurrentDir = fiCurrent.DirectoryName;
            if (!strCurrentDir.EndsWith("\\"))
                strCurrentDir += "\\";


            File.WriteAllText(strCurrentDir+"run.bat", fileName);
            ProcessStartInfo prStartInfo = new ProcessStartInfo();
            prStartInfo.FileName = strCurrentDir+ "run.bat";
            if (winVersion >= 5.2)
            {
                prStartInfo.Verb = "runas";
            }
            prStartInfo.UseShellExecute = true;
            prStartInfo.WindowStyle = ProcessWindowStyle.Hidden;
            Process prNew = new Process();
            prNew.StartInfo = prStartInfo;
            prNew.Start();
            prNew.WaitForExit();
        }

        [DllImport("USER32.DLL")]
        private static extern int BringWindowToTop(IntPtr hwnd);



        private void Browser_Closed(object sender, EventArgs e)
        {
            RegistryKey key;
            if (this.oIESettings[0] != null)
            {
                key = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Internet Settings\Connections", true);
                key.SetValue("DefaultConnectionSettings", this.oIESettings[0]);
                key.Close();
            }
            if (this.oIESettings[1] != null)
            {
                key = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Internet Settings", true);
                key.SetValue("AutoConfigURL", this.oIESettings[1]);
                key.Close();
            }
            Application.Exit();
        }



        private void Browser_Load(object sender, EventArgs e)
        {
            this.Text = ConfigurationSettings.AppSettings["Title"];
            if (!this.IsHarfWebCDInitRunning())
            {
                MessageBox.Show("تعذر تشغيل البرنامج لأن محرك الويب سىدى لا يعمل");
                Application.Exit();
            }
            else
            {
                if (!this.IsRunRequirmentExist())
                {
                    Application.Exit();
                }
                if (this.IsOtherInstantRunning())
                {
                    Application.Exit();
                }
                int appPort = this.GetAppPort("FatawaBaz");
                int num2 = this.GetAppPort("FatawaBazService");
                if ((appPort < 0) || (num2 < 0))
                {
                    MessageBox.Show("لايوجد free port , لا يمكن تشغيل البرنامج");
                    Application.Exit();
                }
                else
                {
                    this.ModifyConfigFiles(appPort, num2);
                }
            }
        }




        private bool CheckRealPlayerInstall()
        {
            return (Registry.CurrentUser.OpenSubKey(@"Software\RealNetworks\RealPlayer") != null);
        }




        private bool CheckWord()
        {
            return (Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Office\Word") != null);
        }




        protected override void Dispose(bool disposing)
        {
            if (disposing && (this.components != null))
            {
                this.components.Dispose();
            }
            base.Dispose(disposing);
        }




        private int GetAppPort(string strPortTitle)
        {
            RegistryKey key = Registry.LocalMachine.OpenSubKey(@"Software\Harf\WebCDInit\" + strPortTitle, true);
            if (key == null)
            {
                return -1;
            }
            int ret = -1;
            int i = 0;
            
            while (i <= 180)
            {
               
                try
                {
                    ret = int.Parse(key.GetValue(null).ToString());
                    return ret;
                }
                catch
                {
                    i++;
                    Thread.Sleep(1000);
                    
                    
                }
            }
                
            return -1;
        }




        private string GetIExplorePath()
        {
            RegistryKey key = Registry.LocalMachine.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\App Paths\IEXPLORE.EXE");
            if (key != null)
            {
                return (string)key.GetValue("Path");
            }
            return string.Empty;
        }




        //private void ie_BeforeNavigate2(object sender, DWebBrowserEvents2_BeforeNavigate2Event e)
        //{
        //    switch (((string)e.uRL).ToLower())
        //    {
        //        case "javascript:%20minmize();":
        //            e.cancel = true;
        //            base.WindowState = FormWindowState.Minimized;
        //            break;

        //        case "javascript:%20close();":
        //            e.cancel = true;
        //            Application.Exit();
        //            break;
        //    }
        //}

        //private void ie_Leave(object sender, EventArgs e)
        //{
        //    Application.Exit();
        //}




        private void InitializeComponent()
        {
            //ResourceManager manager = new ResourceManager(typeof(Browser));
            this.saveFileDialog = new SaveFileDialog();
            this.ie = new WebBrowser(); //new AxWebBrowser();
            //this.ie;
            base.SuspendLayout();
            this.saveFileDialog.DefaultExt = "pdf";
            this.saveFileDialog.Filter = "pdf Files |*.pdf|All files|*.*";
            this.ie.Dock = DockStyle.Fill;
            //this.ie.Enabled = true;
            this.ie.Location = new Point(0, 0);
            //this.ie.OcxState = (AxHost.State)manager.GetObject("ie.OcxState");
            this.ie.Size = new Size(0x338, 0x1c8);
            this.ie.TabIndex = 0;
            this.ie.Navigating += new WebBrowserNavigatingEventHandler(ie_Navigating);
            this.ie.Navigated += new WebBrowserNavigatedEventHandler(ie_Navigated);

            //this.ie.BeforeNavigate2 += new DWebBrowserEvents2_BeforeNavigate2EventHandler(this.ie_BeforeNavigate2);
            //this.ie.Leave += new EventHandler(this.ie_Leave);
            ie.LostFocus += new EventHandler(ie_LostFocus);
            this.AutoScaleBaseSize = new Size(5, 13);
            base.ClientSize = new Size(0x338, 0x1c8);
            base.Controls.Add(this.ie);
            base.FormBorderStyle =System.Windows.Forms.FormBorderStyle.None;
            base.Icon = this.Icon;// (Icon)manager.GetObject("$this.Icon");
            base.Name = "Browser";
            base.StartPosition = FormStartPosition.CenterParent;
            this.Text = "Browser";
            base.WindowState = FormWindowState.Maximized;
            base.Load += new EventHandler(this.Browser_Load);
            base.Closed += new EventHandler(this.Browser_Closed);

            //this.ie.EndInit();
            base.ResumeLayout(false);
        }

        void ie_Navigated(object sender, WebBrowserNavigatedEventArgs e)
        {
            if (back)
            {
                if (ie.Url.AbsoluteUri.ToLower().Contains("PrintFatwa2.aspx".ToLower()))
                {
                    ie.GoBack();
                    
                }
                else
                {
                    back = false;
                    //ie.GoBack();
                }
                return;

            }
           

            
                if (e.Url.AbsoluteUri.ToLower().Contains("PrintFatwa2.aspx".ToLower()))
                {
                    
                        
                        string newUrl = getPrintUrl(e.Url.AbsoluteUri);
                        if (newUrl.ToLower() != e.Url.AbsoluteUri.ToLower())
                        {


                            ie.Navigate(newUrl);
                        }
                    
                }


                
        }

        void ie_LostFocus(object sender, EventArgs e)
        {
            //Application.Exit();
        }

        bool back = false;

        void ie_Navigating(object sender, WebBrowserNavigatingEventArgs e)
        {
            switch (((string)e.Url.AbsoluteUri).ToLower())
            {
                case "javascript:%20minmize();":
                    e.Cancel = true;
                    base.WindowState = FormWindowState.Minimized;
                    break;

                case "javascript:%20close();":
                    e.Cancel = true;
                    Application.Exit();
                    break;
                case "javascript:%20history.back(1);":
                    if (ie.Url.AbsoluteUri.ToLower().Contains("PrintFatwa2.aspx".ToLower()))
                    {
                        back = true;
                    }
                    
                    break;
            }


          


            
        }

        private string getPrintUrl(string p)
        {
            string ret = p;
            try
            {
                Regex reg = new Regex(@"ID\=[0-9,]+", RegexOptions.IgnoreCase);
                Match mch = reg.Match(p);
                if (mch.Success)
                {
                    string[] number = mch.Value.Substring(3).Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

                    string newBook = "";

                    foreach (string strNum in number)
                    {
                        if (newBook == "")
                            newBook = "4";
                        else
                            newBook += ",4";
                    }

                    ret = p.Substring(0, p.LastIndexOf("=") + 1) + newBook;
                }
            }
            catch
            {
                ret = p;
            }

            return ret;
        }

        private bool IsHarfWebCDInitRunning()
        {
            return (Process.GetProcessesByName("HarfWebCDInit").Length != 0);
        }




        [DllImport("user32.dll")]
        private static extern bool IsIconic(IntPtr hWnd);



        private bool IsOtherInstantRunning()
        {
            Process currentProcess = Process.GetCurrentProcess();
            foreach (Process process2 in Process.GetProcessesByName(currentProcess.ProcessName))
            {
                if (currentProcess.Id != process2.Id)
                {
                    IntPtr mainWindowHandle = process2.MainWindowHandle;
                    if (IsIconic(mainWindowHandle))
                    {
                        ShowWindowAsync(mainWindowHandle, 9);
                    }
                    SetForegroundWindow(mainWindowHandle);
                    return true;
                }
            }
            return false;
        }




        private bool IsRunRequirmentExist()
        {
            RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\DataAccess");
            if (key == null)
            {
                MessageBox.Show(this, "يجب أعادة تشغيل الجهاز", this.Text);
                Application.Exit();
                return false;
            }
            object obj2 = key.GetValue("FullInstallVer");
            try
            {
                if ((obj2 != null) && (double.Parse(obj2.ToString().Substring(0, 3)) >= 2.6))
                {
                    return true;
                }
            }
            catch
            {
                return false;
            }
            MessageBox.Show(this, "يجب أعادة تشغيل الجهاز", this.Text);
            return false;
        }




        private void ModifyConfigFiles(int nPort1, int nPort2)
        {
            //string currentDirectory = Directory.GetCurrentDirectory();
            FileInfo fiStarter = new FileInfo( System.Reflection.Assembly.GetExecutingAssembly().Location);
            string currentDirectory = fiStarter.DirectoryName;
            this.strDefDir = (currentDirectory.EndsWith(@"\") ? currentDirectory : (currentDirectory + @"\")) + ConfigurationSettings.AppSettings["Root"];
            ReadConfig.writeConfigServer(this.strDefDir + @"\ExesFiles\dataconfiguration.config", serverName);
            //if (!File.Exists(this.strDefDir + @"\ConfigCenter\dataconfiguration.config"))
            //{
                File.Copy(this.strDefDir + @"\ExesFiles\dataconfiguration.config", this.strDefDir + @"\ConfigCenter\dataconfiguration.config", true);
            //}
            StreamReader reader = new StreamReader(this.strDefDir + @"\ExesFiles\Web.config", Encoding.Default);
            string str2 = reader.ReadToEnd();
            reader.Close();
            str2 = str2.Replace("(CassiniLightPort)", nPort2.ToString()).Replace("(CassiniLightMPort)", nPort1.ToString());
            reader = new StreamReader(this.strDefDir + @"\Web.config", Encoding.Default);
            if (str2 == reader.ReadToEnd())
            {
                reader.Close();
            }
            else
            {
                reader.Close();
                StreamWriter writer = new StreamWriter(this.strDefDir + @"\Web.config", false, Encoding.Default);
                writer.Write(str2);
                writer.Close();
            }




            string strSourceFile = this.strDefDir + @"\ExesFiles\WebService.config";

            
            

            string strServiceConfig = this.strDefDir+ "\\WebService1\\Web.config";

            File.Copy(strSourceFile,strServiceConfig,true);

            ReadConfig.writeServiceConfigServer(strServiceConfig, serverName);
            


            this.strURL = string.Format("http://127.0.0.1:{0}/", nPort1);
            string uRL = this.strURL + ConfigurationSettings.AppSettings["Home"];
            object flags = null;


            bool bStarted = false;

            int i = 0;

            while ((!bStarted) && i<20)
            {

                try
                {
                    HttpWebRequest hwr = HttpWebRequest.Create(uRL) as HttpWebRequest;

                    HttpWebResponse hrr = hwr.GetResponse() as HttpWebResponse;


                    bStarted = true;

                }
                catch
                {
                    bStarted = false;
                    Thread.Sleep(1000);
                }
                i++;
            
            }
            
            

            this.ie.Navigate(uRL);//, ref flags, ref flags, ref flags, ref flags);
        }




        [DllImport("WINMM.DLL")]
        private static extern int PlaySound(string name, int hmod, int flages);



        private void PlayWaveSound(string strFile)
        {
            PlaySound(strFile, 0, 0x20000);
        }




        private bool PortIsFree(int Port)
        {
            TcpClient client = new TcpClient();
            try
            {
                client.Connect("localhost", Port);
                return false;
            }
            catch
            {
                return true;
            }
        }




        [DllImport("user32.dll")]
        private static extern bool SetForegroundWindow(IntPtr hWnd);



        [DllImport("Shell32.dll")]
        private static extern int ShellExecute(int hwnd, string lpOperation, string lpFile, string lpParameters, string lpDirectory, int nShowCmd);



        [DllImport("USER32.DLL")]
        private static extern int ShowWindow(IntPtr hwnd, int nCmdShow);



        [DllImport("user32.dll")]
        private static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow);



        private bool bSoundFromCD;



        private Container components;


        private WebBrowser ie;



        private object[] oIESettings;



        private SaveFileDialog saveFileDialog;



        private string strDefDir;

        private const string strSavePattern = "?save=true";



        private string strURL;


        private const int SW_RESTORE = 9;


 

    }
}
